/**
 * 上传文件需要
 * @param url
 */
import { ossAccessGetApi, uploadFile } from '@/api/attendance/index.js';
import moment from 'moment';
/**
 * 上传文件需要
 * @param url
 */

const bucketName = process.env.VUE_APP_MODE === 'pro' ? 'saas-prod' : 'saas-dormitory';
const baseUrlData =
  process.env.VUE_APP_MODE === 'pro'
    ? 'https://saas-prod.obs.cn-east-3.myhuaweicloud.com/'
    : 'https://saas-dormitory.obs.cn-east-3.myhuaweicloud.com/';

const directory = process.env.VUE_APP_MODE === 'pro' ? 'dormitory/' : 'assets/';

const renderSize = value => {
  if (value == null || value === '') {
    return '0 B';
  }
  let unitArr = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  let index = 0;
  let srcsize = parseFloat(value);
  index = Math.floor(Math.log(srcsize) / Math.log(1024));
  let size = srcsize / Math.pow(1024, index);
  let getSize = String(size.toFixed(2));
  return getSize + unitArr[index];
};
const fileStrInfo = file => {
  return {
    type: file.replace(/.+\./, ''),
    filename: file.replace(/(.*\/)*([^.]+).*/gi, '$2')
  };
};
export const filesParams = file => {
  let name = new Date().getTime() + '_' + file.name;
  return {
    name: name, // 文件全名
    fileName: fileStrInfo(name).filename, // 文件名
    fileSuffix: fileStrInfo(name).type, // 文件后缀名
    size: file.size,
    formatSize: renderSize(file.size), // 格式化后的文件大小
    raw: file // 原始文件
  };
};
export function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
async function getOssInfo(dir) {
  return await ossAccessGetApi({
    bucketName: bucketName,
    dir
  });
}
export function uploadOssFile(file) {
  return new Promise(function (resolve, reject) {
    const { name, size } = filesParams(file);
    let date = new Date();
    console.log(file, '++++++uid');
    let uid = file.uid;
    let fileType = file.fileType;
    let dateStr = moment().format('YYYY-MM-DD');
    const dir = directory + dateStr + '/' + file.lastModified + '_' + file.name;
    console.log(dir);
    // const dir = 'oa';
    const baseUrl = baseUrlData + dir;
    getOssInfo(dir).then(res => {
      console.log(res);
      const { Accesskeyid, Signature, Policy } = res.data.data;
      console.log(Accesskeyid);
      const formData = new FormData();
      formData.append('key', dir);
      formData.append('AccessKeyId', Accesskeyid);
      formData.append('signature', Signature);
      formData.append('policy', Policy);
      formData.append('file', file);
      uploadFile(formData);
      resolve({ url: baseUrl, uid: uid, size, name: file.name, fileType: fileType }); // 返回
    });
  });
}
